package com.huanzhidadi.springsecurity.config;

import com.huanzhidadi.springsecurity.model.LoginUser;
import org.springframework.core.task.TaskDecorator;

/**
 * @author
 * @description 上下文装饰器
 */
public class ContextTaskDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(Runnable runnable) {
        //获取父线程的loginUser
        LoginUser loginUser = UserContextHolder.currentLoginUser();
        return () -> {
            try {
                // 将主线程的请求信息，设置到子线程中
                UserContextHolder.set(loginUser);
                // 执行子线程，这一步不要忘了
                runnable.run();
            } finally {
                // 线程结束，清空这些信息，否则可能造成内存泄漏
                UserContextHolder.shutdown();
            }
        };
    }
}